import cookie from "cookie";
import env from "../env";

const COOKIE_SECURE = env.server.cookie.secure;

function serialize(name: string, value: string, expireTime: Date): string {
  return cookie.serialize(name, value, {
    httpOnly: true,
    expires: expireTime,
    secure: COOKIE_SECURE,
    sameSite: true,
    path: "/",
  });
}

function discard(name: string): string {
  return cookie.serialize(name, "", {
    httpOnly: true,
    maxAge: 0,
    secure: COOKIE_SECURE,
    sameSite: true,
    path: "/",
  });
}

function getCookies(headers: Headers): Record<string, string> {
  const cookieStr = headers.get("Cookie");
  return cookieStr ? cookie.parse(cookieStr) : {};
}

const cookieService = {
  serialize,
  discard,
  getCookies,
};

export default cookieService;
